package com.jy.oms.framework.asyn.task.alarm;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.jy.oms.framework.asyn.task.core.ExecutorContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 飞书告警
 * @author liuquan
 */
public class FeishuAlarmMessageService implements ITaskAlarmMessageService{
    private static Logger logger = LoggerFactory.getLogger(FeishuAlarmMessageService.class);

    private static final String WEBHOOK_ADDRESS = "https://open.feishu.cn/open-apis/bot/v2/hook/";

    private final String robotKey;

    public FeishuAlarmMessageService(String robotKey) {
        this.robotKey = robotKey;
    }

    @Override
    public void alarm(AlarmMessage alarmMessage) {
        if (ExecutorContext.isDev()) {
            logger.error(alarmMessage.toString());
        } else {
            logger.error(alarmMessage.toString());

            this.alarm(alarmMessage.toString());
        }
    }
    
    public void alarm(String msg){
        if (StringUtils.isAnyBlank(robotKey)) {
            return;
        }

        try {
            JSONObject text = new JSONObject().fluentPut("text", msg);
            String msgJson = new JSONObject().fluentPut("msg_type", "text")
                    .fluentPut("content", text).toJSONString();

            HttpUtil.post(WEBHOOK_ADDRESS + robotKey, msgJson, 5000);
        } catch (Exception e) {
            logger.error("发送消息失败", e);
        }
    }
}
